﻿

namespace SvGame.Controller;

public partial class GameHandler
{
    /// <summary>
    /// 玩家登录
    /// </summary>
    /// <param name="pack"></param>
    public int C2GPlayerLogin(MyPackage pack)
    {
        pack.GetMsg(out C2GPlayerLogin req);
        var rsp = new G2CPlayerLogin();

        if (pack.PackGetLoginPlayer(out var _))
        {
            return pack.Send(rsp, EProtocolResult.重复登录);
        }

        // todo C2GPlayerLogin 验证账号验证码

        rsp.Puid = DbRedis.GetUuidPuid(req.UserId, SvInfo.ConfigId);
        if (rsp.Puid == 0)
        {
            return pack.Send(rsp);
        }
        if (GetPlayer(rsp.Puid, out var player))
        {
            // 判断顶号
            if (player.Session.SessionID != pack.Session.SessionID)
            {
                var msgReplace = new G2CPlayerReplace();
                player.Session.Send(msgReplace);
            }
        }
        else
        {
            player = new()
            {
                Puid = rsp.Puid,
            };
            if (DbRedis.ZLoad(ref player))
            {

            }
            else
            {
                return pack.Send(rsp, EProtocolResult.失败);
            }
        }

        player.BindSession(pack.Session);
        GameLogic.PlayerLogin(player);

        return pack.Send(rsp);
    }
    /// <summary>
    /// 玩家创建
    /// </summary>
    /// <param name="pack"></param>
    public int C2GPlayerCreate(MyPackage pack)
    {
        pack.GetMsg(out C2GPlayerCreate req);
        var rsp = new G2CPlayerCreate();

        if (pack.PackGetLoginPlayer(out var _))
        {
            return pack.Send(rsp, EProtocolResult.重复登录);
        }

        // todo C2GPlayerCreate 验证账号验证码

        if (req.Name == "8i9o0p")
        {
            req.Name = NameMgr.GetName(req.Gender);
            req.Talent = new InfoTalent()
            {
                Str = 20,
                Int = 20,
                Spi = 20,
                Con = 20,
                Cps = 20,
                Cor = 20,
                Per = 20,
                Kar = 20,
            };
            req.Family = ConfFamily.Keys.RandomSingle();
        }
        var rst = GameLogic.CheckPlayerName(req.Name);
        if (!rst.Success())
        {
            return pack.Send(rsp, rst);
        }
        if (!GameLogic.TalentCheckCreate(req.Talent))
        {
            return pack.Send(rsp, EProtocolResult.初始天赋错误);
        }
        var puid = IdMgr.CreatePuid();
        if (puid == 0)
        {
            return pack.Send(rsp, EProtocolResult.服务器数据库异常);
        }
        Player player = new()
        {
            Uuid = req.UserId,
            Puid = puid,
            Session = pack.Session,
        }; 
        

        PlayerCreate(player, puid, req);
        CreateSave(player);
        player.BindSession(pack.Session);
        PlayerLogin(player);

        rsp.Puid = puid;

        DbRedis.ZSave(player);

        return pack.Send(rsp);
    }
}
